package logic

import (
	"context"
	"fmt"
	"login/models/mysql"
	"login/pkg"

	"login/loginrpc/internal/svc"
	"login/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *loginrpc.LoginUserRequest) (*loginrpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line

	var userFin mysql.User
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&userFin)
	if userFin.ID == 0 {
		return nil, fmt.Errorf("用户不存在,请先注册")
	}

	var user mysql.User
	err := mysql.DB.Debug().Where("name = ?", in.Name).Find(&user).Error
	if err != nil {
		return nil, fmt.Errorf("登录失败")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}

	return &loginrpc.LoginUserResponse{Id: int64(user.ID)}, nil
}
